package com.isunland.managesystem.ui;

import android.app.Activity;
import com.isunland.managesystem.adapter.LatestAnnounceMentAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.view.View;
import android.widget.ListView;

import com.google.gson.Gson;
import com.isunland.managesystem.adapter.MessageReceiveListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.HintNumber;
import com.isunland.managesystem.entity.MassageReceiveOriginal;
import com.isunland.managesystem.entity.Message;

//import android.widget.TextView;

public class MessageReceiveListFragment extends BaseListFragment {

  protected static final String TAG = "ReceiveMassageFragment";
  private final int REQUEST_DETAIL = 0;
  private ArrayList<Message> mMessageReceiveList;
  private MessageReceiveListAdapter mAdapter;

  private List<Message> mReceivemessage;
  private Message message;

  @Override public String getUrl() {
    return ApiConst.URL_MASSAGE_RECEIVE;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("curPage", "1");
    params.put("pageSize", "1000");
    return params;
  }

  @Override public void resolveResponse(String arg0) {

    MassageReceiveOriginal receiveMassageOriginal =
        new Gson().fromJson(arg0, MassageReceiveOriginal.class);

    mReceivemessage = receiveMassageOriginal.getRows();
    setAdapter(mReceivemessage);
  }

  private void setAdapter(List<Message> receivemessage) {

    if (mMessageReceiveList == null) {
      mMessageReceiveList = new ArrayList<Message>();
    }
    mMessageReceiveList.clear();
    mMessageReceiveList.addAll(receivemessage);
    if (mAdapter == null) {
      mAdapter = new MessageReceiveListAdapter(getActivity(), mMessageReceiveList);
      setListAdapter(mAdapter);
    }
    ((MessageReceiveListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    message = mMessageReceiveList.get(position - 1);
    Intent i = new Intent(getActivity(), MessageDetailActivity.class);
    i.putExtra(MessageDetailFragment.EXTRA_MESSAGE, message);
    i.putExtra(MessageDetailFragment.EXTRA_TYPE, MessageDetailFragment.VALUE_RECEIVE);
    startActivityForResult(i, REQUEST_DETAIL);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_DETAIL) {
      //改为已读刷新列表
      message.setIfRead("T");
      ((MessageReceiveListAdapter) getListAdapter()).notifyDataSetChanged();
      HintNumber.newInstance(getActivity()).reduce(HintNumber.MESSAGE);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
